import {Component, Input, OnChanges, OnInit, ViewChild, SimpleChanges} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {EquipMainDataHttpServices} from '../http/http';
import {HttpErrorResponse} from '@angular/common/http';
import {Util, ParentCategory} from './util';


interface DeviceDefCategoryTableItem {
  code: string;
  name: string;
  parentName: string;
  createUserName: string;
  createTime: string;
  parentId: number;
  id: number;
}

@Component({
  selector: `device-def-category-form`,
  styleUrls: ['./components.less'],
  template: `
    <form nz-form [formGroup]="defCategoryMgmtForm" class="attr-type-form">
      <nz-form-item>
        <nz-form-label nzRequired [nzSpan]="8">
          编码
        </nz-form-label>
        <nz-form-control nzErrorTip="请输入内容" [nzSpan]="16">
          <input nz-input formControlName="code"/>
        </nz-form-control>
      </nz-form-item>
      <nz-form-item>
        <nz-form-label nzRequired [nzSpan]="8">
          名称
        </nz-form-label>
        <nz-form-control nzErrorTip="请输入内容" [nzSpan]="16">
          <input nz-input formControlName="name"/>
        </nz-form-control>
      </nz-form-item>
      <nz-form-item>
        <nz-form-label [nzSpan]="8" [nzRequired]="false">
          父分类
        </nz-form-label>
        <nz-form-control [nzSpan]="16">
          <nz-cascader [nzOptions]="parenetsData" formControlName="parentId" nzChangeOnSelect
                       (nzSelectionChange)="onChanges($event)" (nzClear)="currentSelectedData = {id:null,name:null}"></nz-cascader>
        </nz-form-control>
      </nz-form-item>
    </form>
  `
})

export class DeviceDefCategoryFormComponent implements OnChanges, OnInit {
  constructor(private fb: FormBuilder, private http: EquipMainDataHttpServices, private util: Util) {
  }

  @Input() mode: string;
  @Input() editData: DeviceDefCategoryTableItem;
  @Input() defCategoryMgmtForm!: FormGroup;
  parenetsData: any;
  currentSelectedData = {
    id: null,
    name: null,
    allParentId: null,
    allParentName: null
  };

  onCreate(successCallback): void {
    if (this.defCategoryMgmtForm.valid) {
      const {code, name} = this.defCategoryMgmtForm.value;
      this.http.createDeviceDefCategory({
        code,
        name,
        parentId: this.currentSelectedData && this.currentSelectedData.id,
        parentName: this.currentSelectedData && this.currentSelectedData.name,
        allParentId: this.currentSelectedData && this.currentSelectedData.allParentId,
        allParentName: this.currentSelectedData && this.currentSelectedData.allParentName
      }).subscribe((res) => {
        if (res.code === 0) {
          successCallback();
          this.currentSelectedData = {
            id: null,
            name: null,
            allParentId: null,
            allParentName: null
          };
        }
      }, (err: HttpErrorResponse) => {
      });
    }
  }

  onUpdate(successCallback): void {
    const parentId = this.currentSelectedData.id ? this.currentSelectedData.id : null;
    const parentName = this.currentSelectedData.name ? this.currentSelectedData.name : null;
    const allParentId = this.currentSelectedData && this.currentSelectedData.allParentId;
    const allParentName = this.currentSelectedData && this.currentSelectedData.allParentName;
    this.http.updateDeviceDefCategory({
      ...this.defCategoryMgmtForm.value, parentId, parentName, allParentId, allParentName,id: this.editData.id
    })
      .subscribe((res) => {
        if (res.code === 0) {
          successCallback();
          this.currentSelectedData = {
            id: null,
            name: null,
            allParentId: null,
            allParentName: null
          };
        }
      }, (err: HttpErrorResponse) => {
      });
  }

  onChanges(array: Array<ParentCategory>): void {
    const idArray = [], nameArray = [];
    for (let item of array) {
      idArray.push(item.id);
      nameArray.push(item.name);
    }
    this.currentSelectedData = {
      id: array[array.length - 1].id,
      name: array[array.length - 1].name,
      allParentId: idArray.join(','),
      allParentName: nameArray.join(',')
    };
    console.log(this.currentSelectedData);
  }

  ngOnChanges(changes: SimpleChanges): void {
    if (this.mode !== 'create' && this.editData && this.defCategoryMgmtForm) {

      const cascadeData = this.util.getCascaderDataY(this.editData);
      this.defCategoryMgmtForm.patchValue({...this.editData, parentId: cascadeData});
    }
  }

  ngOnInit(): void {
    this.http.getAllDeviceParentsCategories().subscribe((res) => {
      this.parenetsData = this.util.getCascaderData(res.data);
    }, (error: HttpErrorResponse) => {
    });
  }
}

@Component({
  selector: 'app-equip-device-def-category-mgmt',
  styleUrls: ['./components.less'],
  template: `
    <div class="equipMainDataMgmtContainer">
      <div class="equip-main-data-mgmt-bar">
        <div><span>单位码：</span><input nz-input placeholder="输入类型编码查询" [(ngModel)]="keyword"/></div>
        <button nz-button nzType="primary" (click)="loadTable()">查询</button>
        <button nz-button style="background:'green';color:'#ffffff';border-color:'transparent'" (click)="visibleObject.toForm = true">新增
        </button>
      </div>
      <nz-table #defCategoryTable nzSize="middle" [nzShowSizeChanger]="true" [nzShowQuickJumper]="true"
                [nzData]="tableData" [nzLoading]="loading" [nzFrontPagination]="false"
                [nzTotal]="pagination.total" [(nzPageSize)]="pagination.size" [(nzPageIndex)]="pagination.start"
                (nzPageIndexChange)="onPageIndexChange($event)" (nzPageSizeChange)="onPageSizeChange($event)">
        <thead>
        <tr>
          <th>编码</th>
          <th>名称</th>
          <th>父分类</th>
          <th>创建人</th>
          <th>创建时间</th>
          <th nzAlign="center">操作</th>
        </tr>
        </thead>
        <tbody>
        <tr *ngFor="let defItem of defCategoryTable.data">
          <td>{{ defItem.code }}</td>
          <td>{{ defItem.name }}</td>
          <td>{{ defItem.parentName }}</td>
          <td>{{ defItem.createUserName }}</td>
          <td>{{ defItem.createTime }}</td>
          <td class='option-td' nzAlign="center">
            <span (click)="onEdit(defItem)">修改</span>
            <span (click)="visibleObject.toDelete = true; deleteId = defItem.id">删除</span>
          </td>
        </tr>
        </tbody>
      </nz-table>
    </div>


    <nz-modal [(nzVisible)]="visibleObject.toForm" [nzTitle]="modalTitle" (nzOnCancel)="onCancel()"
              (nzOnOk)="onSubmit()" [nzWidth]="744">
      <ng-template #modalTitle>新增属性定义分类</ng-template>
      <ng-container *nzModalContent>
        <device-def-category-form #myForm [mode]="mode" [editData]="editData"
                                  [defCategoryMgmtForm]="attrDefCategoryMgmtForm"></device-def-category-form>
      </ng-container>
    </nz-modal>

    <nz-modal [(nzVisible)]="visibleObject.toDelete" nzTitle="警告" (nzOnCancel)="visibleObject.toDelete=false" (nzOnOk)="onDelete()">
      <ng-container *nzModalContent>
        您确认要删除此项吗？
      </ng-container>
    </nz-modal>
  `
})
export class DeviceDefCategoryMgmtComponent implements OnInit {
  constructor(private http: EquipMainDataHttpServices, private fb: FormBuilder) {
  }

  @ViewChild('myForm') formComponent;
  attrDefCategoryMgmtForm!: FormGroup;
  mode = 'create';
  tableData!: Array<DeviceDefCategoryTableItem>;
  editData!: DeviceDefCategoryTableItem;
  visibleObject: any = {
    toForm: false,
    toDelete: false
  };
  loading = true;
  keyword = '';
  deleteId: any;
  pagination: any = {
    size: 10,
    start: 1,
    total: undefined,
  };

  loadTable(): void {
    const {start, size} = this.pagination;
    this.http.queryDeviceDefCategory({start: start - 1, size, keyword: this.keyword}).subscribe(
      (res) => {
        if (res.code === 0) {
          this.tableData = res.data.content;
          this.pagination.total = res.data.totalElements;
          this.loading = false;
        }
      }, (err: HttpErrorResponse) => {
        this.loading = false;
        this.tableData = [];
      });
  }

  onSubmit(): void {
    if (this.mode === 'create') {
      this.formComponent.onCreate(() => {
        this.loadTable();
        this.attrDefCategoryMgmtForm.reset();
      });
    } else {
      this.formComponent.onUpdate(() => {
        this.loadTable();
        this.mode = 'create';
        this.attrDefCategoryMgmtForm.reset();
      });
    }
    this.visibleObject.toForm = false;
  }


  onCancel(): void {
    this.visibleObject.toForm = false;
    this.mode = 'create';
    this.attrDefCategoryMgmtForm.reset();
  }

  onEdit(data): void {
    this.visibleObject.toForm = true;
    this.mode = 'edit';
    this.editData = data;
  }

  onDelete(): void {
    this.visibleObject.toDelete = false;
    this.http.deleteDeviceDefCategory(this.deleteId).subscribe(
      (res) => {
        if (res.code === 0) {
          this.loadTable();
        }
      }, (err: HttpErrorResponse) => {
      });
  }

  onPageIndexChange(data): void {
    this.pagination.start = data;
    this.loadTable();
  }

  onPageSizeChange(data): void {
    this.pagination.size = data;
    this.loadTable();
  }

  ngOnInit(): void {
    this.loadTable();
    this.attrDefCategoryMgmtForm = this.fb.group({
      code: [null, Validators.required],
      parentId: [[]],
      name: [null, Validators.required]
      ,
    });
  }

}
